import * as echarts from '../../../components/echarts/echarts';
const app = getApp();
const requestUtil = require("../../../utils/request");
const util = require("../../../utils/util");
const api = require("../../../config/api");
Page({
    /**
     * 页面的初始数据
     */
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        tableNoDataMsg: '暂无数据~',
        fyNum: 1,
        fySize: 10,
        dataList: [],
        qIndex: 0,
        uIndex: 0,
        dIndex: 0,
        betDateName: null,
        dList: [
            {id: 0, name: '本月'},
            {id: 1, name:'本周'},
            {id: 2, name:'上周'},
            {id: 3, name:'上月'},
            {id: 4, name:'自定义区间'},
        ],
        uList: [],
        selectUser: '',
        
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            dIndex: options.dIndex,
            startDate: options.startDate,
            endDate: options.endDate,
            questionId: options.questionId,
            selectUser: options.userName,
        })
        this.formatData();
        this.questionList();
    },
    formatData(){
        let dList = this.data.dList;
        var date = new Date();
        var year = date.getFullYear();//本年
        var month = date.getMonth();//本月
        var week = date.getDay();//当前星期 0.1.2.3.4.5.6[0=周日]
        var time = date.getTime();//当天
        var oneDayTime = 24 * 60 * 60 * 1000;//一天的总ms

        //本月
        dList[0].startDate = util.dateFormat(date, 'yyyy-MM') + '-01';
        dList[0].endDate = util.dateFormat(date, 'yyyy-MM') + '-' + new Date(year, month+1, 0).getDate();

        //本周
        var thisWeekFirst = (1 - week) * oneDayTime + time;
        var thisWeekLast = thisWeekFirst + 6 * oneDayTime;
        dList[1].startDate = util.dateFormat(new Date(thisWeekFirst), 'yyyy-MM-dd');
        dList[1].endDate = util.dateFormat(new Date(thisWeekLast), 'yyyy-MM-dd');

        //上周
        dList[2].startDate = util.dateFormat(new Date(thisWeekFirst - 7*oneDayTime), 'yyyy-MM-dd');
        dList[2].endDate = util.dateFormat(new Date(thisWeekFirst - oneDayTime), 'yyyy-MM-dd');

        //上月
        var preDate = new Date(year, month, 0);
        var lastDay = preDate.getDate();
        dList[3].startDate = util.dateFormat(preDate, 'yyyy-MM')  + '-01';
        dList[3].endDate = util.dateFormat(preDate, 'yyyy-MM') + '-' + lastDay;

        if(this.data.dIndex == 4) {
            dList[4].startDate = this.data.startDate;
            dList[4].endDate = this.data.endDate;
            let startStr = util.dateFormat(new Date(dList[4].startDate), 'yy/M/d');
            let endStr = util.dateFormat(new Date(dList[4].endDate),'yy/M/d');
            this.setData({
                betDateName: startStr + "-" + endStr,
            })
        }else {
            dList[4].startDate = util.dateFormat(date,'yyyy-MM-dd');
            dList[4].endDate = util.dateFormat(date,'yyyy-MM-dd');
        }
        this.setData({
            dList: dList,
        })
    },
    async questionList(){
        let that = this;
        let res = await requestUtil.request("POST", api.urls.questionList, {
            companyId: app.globalData.employeeInfo.companyId,
            userIds: app.globalData.employeeInfo.isAdmin == 0 ? app.globalData.employeeInfo.id : null,
        })
        let qList = res.data.data;
        let qitem = qList[that.data.qIndex];
        qitem = JSON.parse(qitem.questionContent);
        let answerTableHeader = [{label: '员工信息', children: []},{label: '客户评价', children: []}];
        for(var i in qitem.qData) {
            answerTableHeader[0].children.push({prop: qitem.qData[i].title, label: qitem.qData[i].title});
        }
        for(var i in qitem.wData) {
            answerTableHeader[1].children.push({prop: qitem.wData[i].title, label: qitem.wData[i].title, width: 200});
        }
        that.setData({
            qList: qList,
            answerTableHeader: answerTableHeader,
        })
        this.answerTotal();
        this.userList(that.data.questionId);
        this.initData();
    },
    async answerTotal(){
        let that = this;
        let qInfo = that.data.qList[that.data.qIndex];
        let res = await requestUtil.request("POST", api.urls.answerTotal, {
            questionId: that.data.qList[that.data.qIndex].id,
            startDate: that.data.dList[that.data.dIndex].startDate,
            endDate: that.data.dList[that.data.dIndex].endDate,
            userName: that.data.selectUser,
        })
        let utotal = res.data.data[0];
        let questionContent = JSON.parse(qInfo.questionContent);
        let wData = questionContent["wData"];
        let itemList = [];
        for(let i in wData) {
            if('radio,checkbox'.includes(wData[i].type)) {
                let options = wData[i].option;
                let item = {};
                item["title"] = wData[i].title;
                item["children"] = [];
                for(var j in options) {
                    item["children"].push({key: options[j], value: 0})
                }
                itemList.push(item);
            }
        }
        if(utotal.formatData) {
            let list = JSON.parse(utotal.formatData);
            for(let j in list) {
                let keys = list[j].key.split("-");
                for(let k in itemList) {
                    if(itemList[k]["title"] == keys[0]) {
                        for(let y in itemList[k]["children"]) {
                            if(itemList[k]["children"][y]["key"] == keys[1]) {
                                itemList[k]["children"][y]["value"] = list[j].value;
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }
        that.setData({
            utotal: utotal,
            itemList: itemList,
        })
        let ecTotal = this.selectComponent('#ecTotal');
        ecTotal.init((canvas, width, height, dpr) => {
            const lineChart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
            });
            lineChart.setOption(ecTotalOption(that.data));
            return lineChart;
        })
    },
    async initData(idx) {
        let that = this;
        let fyNum = that.data.fyNum;
        let dataList = that.data.dataList;
        if(idx == 0) {
            fyNum = 1;
            dataList = [];
        }
        if(fyNum < 0) return;
        let params = {
            fyNum: fyNum,
            fySize: that.data.fySize,
            questionId: that.data.qList[that.data.qIndex].id,
            userName: that.data.selectUser
        }
        params.startDate = that.data.dList[that.data.dIndex].startDate;
        params.endDate = that.data.dList[that.data.dIndex].endDate;
        let res = await requestUtil.request("POST", api.urls.questionAnswerList, params)
        for(let i in res.data.data.rows) {
            let item = res.data.data.rows[i];
            item.answerContent = JSON.parse(item.answerContent);
            item.createTime = util.dateFormat(new Date(item.createTime),'yyyy-MM-dd HH:mm');
            if(item.questionType == 2) {
                item.status = !item.answerContent["wResult"] ? 0 : 1
            }
            dataList.push(item);
        }
        fyNum = fyNum * that.data.fySize >= res.data.data.total ? -1 : fyNum + 1;
        that.setData({
            dataList: dataList,
            fyNum: fyNum
        });
        wx.hideLoading();
    },
    async userList(qId){
        let that = this;
        let res = await requestUtil.request("GET", api.urls.questionUserList, {questionId: qId});
        that.setData({
            uList: res.data.data,
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.initData();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        
    },
    toolTabSelect(e){
        let index = e.currentTarget.dataset.index;
        wx:wx.navigateTo({
          url: this.data.toolbars[index].url
        })
    },
    questionPickerChange(e) {
        let idx = parseInt(e.detail.value);
        if(this.data.qIndex == idx) return;
        this.setData({
          qIndex: idx
        })
        let qitem = this.data.qList[idx];
        this.answerTotal();
        this.initData(0);
        this.userList(qitem.id);
    },
    datePickerChange(e) {
        let idx = parseInt(e.detail.value);
        if(idx == 4) {
            this.setData({
                modalName: 'zdyDate'
            })
            return;
        }
        if(this.data.dIndex == idx) return;
        this.setData({
          dIndex: idx,
          betDateName: null,
        })
        this.answerTotal();
        this.initData(0);
    },
    changeSelectUser(e) {
        let name = e.detail.value;
        if(this.data.selectUser == name) return;
        this.setData({
            selectUser: name
        })
        this.hideModal();
        this.answerTotal();
        this.initData(0);
    },
    zdyDateChange(e) {
        let name = e.currentTarget.dataset.name;
        let dList = this.data.dList;
        dList[4][name] = e.detail.value;
        this.setData({
            dList: dList,
        })
    },
    sureZdyDate(e) {
        let dList = this.data.dList;
        let startStr = util.dateFormat(new Date(dList[4].startDate), 'yy/M/d');
        let endStr = util.dateFormat(new Date(dList[4].endDate),'yy/M/d');
        this.setData({
            modalName: null,
            betDateName: startStr + "-" + endStr,
            dIndex: 4
        })
        this.answerTotal();
        this.initData(0);
    },
    showModal(e) {
        this.setData({
          modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
        this.setData({
          modalName: null
        })
    },
    toRedic(e) {
        let id = e.currentTarget.dataset.id;
        wx:wx.navigateTo({
          url: "/pages/question/questionDetail/questionDetail?answerId=" + id,
        })
    },
})

function ecTotalOption(data) {
    return {
        title: {
            text: '',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['总计','已完成','未完成']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
        },
        yAxis: {
            type: 'category',
            data: [data.selectUser]
        },
        series: [
            {
                name: '总计',
                type: 'bar',
                label: {
                    show: true
                },
                data: [data.utotal['total']]
            },
            {
                name: '已完成',
                type: 'bar',
                label: {
                    show: true
                },
                data: [data.utotal['finished']]
            },
            {
                name: '未完成',
                type: 'bar',
                label: {
                    show: true
                },
                data: [data.utotal['total'] - data.utotal['finished']]
            }
        ]
    };	
}